<!--
 * @Description: 
 * @Author: 呆龙
 * @Date: 2023-09-16 14:02:38
 * @LastEditTime: 2023-09-18 11:36:53
 * @LastEditors: 呆龙
-->
<template>
  <a-select
    allowClear
    v-model:value="selectValue"
    show-search
    :disabled="disabled ? disabled : false"
    :mode="mode"
    :placeholder="title"
    :style="style"
    :options="selectData"
    :filter-option="filterOption"
    @change="handleChange"
    :fieldNames="fieldNames"
    @select="handleSelect"
    @search="handleSearch"
    :class="radius ? 'radius' : ''"
  >
    <slot name="default"></slot>
    <template v-if="fetching" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup lang="ts">
  import type { SelectProps } from 'ant-design-vue';
  import { ref, CSSProperties, watch, onMounted } from 'vue';
  const props = defineProps<{
    title?: string;
    selectData: any[];
    mode?: string;
    fieldNames?: SelectProps['fieldNames'];
    style?: CSSProperties;
    value?: string | string[] | null | number;
    disabled?: boolean;
    fetching?: boolean;
    radius?: boolean;
  }>();
  onMounted(() => {
    if (props.value) {
      selectValue.value = props.value;
    }
  });
  watch(
    () => props.value,
    () => {
      if (props.value) {
        selectValue.value = props.value;
      }
    }
  );
  const emit = defineEmits<{
    (event: 'update:value', data: string | number): void;
    (event: 'select', data: any): void;
    (event: 'search', data: any): void;
  }>();
  const handleChange = (value: string | number) => {
    emit('update:value', value);
  };
  const filterOption = (input: string, option: any) => {
    return option[props.fieldNames?.label as keyof typeof option].toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  const selectValue = ref<string | string[] | null | undefined | number>(null);

  const handleSelect = (_: any, option: any) => {
    emit('select', option);
  };

  const handleSearch = (val: any) => {
    emit('search', val);
  };
</script>

<style scoped lang="less">
  .radius {
    :deep(.ant-select-selector) {
      border-radius: 6px !important;
    }
  }
</style>
